package com.chenjun.web.controller.sys;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.Constant;
import com.chenjun.common.base.ResultDto;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.service.sys.SysResourceService;
import com.chenjun.core.service.sys.SysUserRoleService;
import com.chenjun.core.service.sys.SysUserService;
import com.chenjun.core.vo.sys.LoginVo;
import com.chenjun.core.vo.sys.UserRoleBean;
import com.chenjun.web.controller.BaseController;

/**
 * 
 * @Description: 首页控制器 
 * @author yanjinyin
 * @date 2017年7月22日 下午2:17:47
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping("")
public class LoginController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(LoginController.class);

	@Autowired
	private SysResourceService sysResourceService;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysUserRoleService sysUserRoleService;
	/**
	 * 
	 * @Description: 跳转到首页 
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:15:06
	 */
	@RequestMapping("index.html")
	public ModelAndView indexHtml() {
		ModelAndView av = new ModelAndView("index");
		return av;
	}
	/**
	 * 
	 * @Description: 跳转到登录页 
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:14:48
	 */
	@RequestMapping("login.html")
	public ModelAndView loginHtml() {
		ModelAndView av = new ModelAndView("login");
		return av;
	}

	/**
	 * 
	 * @Description: 登陆验证
	 * @param request
	 * @param dto
	 * @param errors
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 上午9:33:44
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public ResultDto login(HttpServletRequest request, @Valid LoginVo dto, Errors errors) {
		ResultDto rtDto = new ResultDto();
		// 验证
		if (!hanleErrors(rtDto, errors)) {
			return rtDto;
		}
		try {
			String loginName = dto.getLoginName();
			String password = dto.getPassword();
			UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
			Subject currentUser = SecurityUtils.getSubject();
			if (currentUser.isAuthenticated()) {
				currentUser.logout();
				request.getSession().invalidate();
			}
			currentUser.login(token);

			DataGridModel dgm = new DataGridModel();
			dgm.setStart(0);
			dgm.setRows(1);
			dgm.getParams().put("userName", loginName);
			List<SysUser> users = sysUserService.doListByCondition(dgm);
			Session session = currentUser.getSession();
			if (!CollectionUtils.isEmpty(users)) {
				SysUser user = users.get(0);
				session.setTimeout(3600000l);// 1 hours // 单位ms
				session.setAttribute(Constant.Session.USER.toString(), user);
				dgm = new DataGridModel();
				dgm.setStart(0);
				dgm.setRows(0);
				dgm.getParams().put("userName", user.getUserName());
				dgm.getParams().put("userId", user.getId());
				List<UserRoleBean> urbs = sysUserRoleService.dofListByCondition(dgm);
				session.setAttribute(Constant.Session.USER_ROLE.toString(), urbs.get(0).getRoleName());
			} else {
				session.setAttribute(Constant.Session.USER.toString(), null);
				session.setAttribute(Constant.Session.USER_ROLE.toString(), null);
			}

		} catch (UnknownAccountException u) {
			rtDto.resultWaring();
			rtDto.setMessage(getLocaleMessage("login.account_not_exist"));
		} catch (IncorrectCredentialsException i) {
			rtDto.resultWaring();
			rtDto.setMessage(getLocaleMessage("login.account_password_not_correct"));
		} catch (ExcessiveAttemptsException a) {
			rtDto.resultWaring();
			rtDto.setMessage(getLocaleMessage("login.amounts_of_login_failed"));
		} catch (DisabledAccountException d) {
			rtDto.resultWaring();
			rtDto.setMessage(getLocaleMessage("login.account_disabled"));
		} catch (Exception e) {
			logger.error(e, e);
			rtDto.resultError();
			rtDto.setMessage(getLocaleMessage("login.unknown_exception"));
		}
		return rtDto;
	}

	/**
	 * 
	 * @Description: 登陆注销
	 * @param request
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:15:35
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		request.getSession().invalidate();
		return "redirect:/login.html";
	}
	/**
	 * 检查权限
	 * @Description:  
	 * @param perm
	 * @param request
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:15:49
	 */
	@RequestMapping(value = "/checkPermission/{perm}")
	@ResponseBody
	public ResultDto checkPermission(@PathVariable String perm, HttpServletRequest request) {
		ResultDto dto = new ResultDto();
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.checkPermission(perm);
			dto.setMessage("权限验证成功!");
		} catch (Exception e) {
			dto.resultError();
			dto.setMessage("权限验证失败!");
		}
		return dto;
	}
	/**
	 * 
	 * @Description: 
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:40:18
	 */
	@RequestMapping("/unauthorizedException.html")
	public ModelAndView unauthorizedException() {
		ModelAndView v = new ModelAndView("unauthorizedException");
		return v;
	}
	/**
	 * 
	 * @Description: 跳转到404页面
	 * @param request
	 * @param response
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:16:26
	 */
	@RequestMapping("/404.html")
	public ModelAndView e404(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView v = new ModelAndView("404");
		return v;
	}
	/**
	 * 
	 * @Description: 跳转到500页面 
	 * @param request
	 * @param response
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:16:42
	 */
	@RequestMapping("/500.html")
	public ModelAndView e500(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView v = new ModelAndView("500");
		return v;
	}
	/**
	 * 
	 * @Description: 跳转到未发现页面 
	 * @param request
	 * @param response
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月22日 下午2:17:03
	 */
	@RequestMapping("/notFound.html")
	public ModelAndView eNotFound(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView v = new ModelAndView("notFound");
		return v;
	}
}
